package com.rgs.gateway.web.common.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author RenGaoshuai
 * @date 2024/7/10 9:26
 * @description 自定义spring的后置处理器，在bean创建的时候先后执行两个方法
 */
@Slf4j
@Component //执行时ioc容器已创建，可以使用该注解
public class TimeCostBeanPostProcessor implements BeanPostProcessor {

    private Map<String, Long> beanCreateCostMap = new ConcurrentHashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //bean创建前执行
        beanCreateCostMap.put(beanName, System.currentTimeMillis());
        return bean;
    }


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //bean创建后执行
        if (beanCreateCostMap.containsKey(beanName)) {
            long start = beanCreateCostMap.get(beanName).longValue();
            long cost = System.currentTimeMillis() - start;
            if (cost > 0) {
                beanCreateCostMap.put(beanName, cost);
                log.info("beanName:{},cost:{}毫秒", beanName, cost);
            }

        }
        return bean;
    }
}
